using System;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Weazel.Toad.Application.Forms
{
  public partial class ProgressForm : Form
  {
    private static ProgressForm form;
    private static string caption;
    private static Thread thread;
    private static AutoResetEvent formReadyEvent = new AutoResetEvent(false);

    private delegate void CloseFormDlg();
    private delegate void UpdateFormDlg(string text);

    public static void Show(string caption)
    {
      ProgressForm.caption = caption;
      thread = new Thread(new ThreadStart(threadBody));
      thread.Start();
      formReadyEvent.WaitOne();
    }

    public static void UpdateProgress(string text)
    {
      form.Invoke(new UpdateFormDlg(updateForm), new object[] { text } );
    }

    public static void CloseOpenForm()
    {
      form.Invoke(new CloseFormDlg(closeForm));
      form = null;
    }

    private static void updateForm(string text)
    {
      form.label1.Text = text;
    }

    private static void closeForm()
    {
      form.Close();
    }

    private static void threadBody()
    {      
      form = new ProgressForm();
      form.Text = caption;

      System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
      timer.Tick += new EventHandler(timer_Tick);
      timer.Start();          
      System.Windows.Forms.Application.Run(form);

      timer.Stop();
      timer.Dispose();
    }

    static void timer_Tick(object sender, EventArgs e)
    {
      form.progressBar1.Value = 
        (form.progressBar1.Value + 10) % form.progressBar1.Maximum;
    }

    protected override void OnLoad(EventArgs e)
    {
      formReadyEvent.Set();  
    }

    public ProgressForm()
    {
      InitializeComponent();
    }
  }
}